package com.hsteach.service.patrol;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hsteach.common.core.page.TableDataInfo;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import com.hsteach.dao.domain.patrol.Behavior;
import com.hsteach.dao.domain.patrol.InspectionDetail;
import com.hsteach.dao.mapper.InspectionMapper;
import com.hsteach.enums.BaseConfigEnum;
import com.hsteach.enums.DeleteStatusEnum;
import com.hsteach.enums.StatusEnum;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetSchoolPartTreeRet;
import com.hsteach.service.third.XgkService;
import com.hsteach.util.JsonUtils;
import com.hsteach.web.controller.patrol.dto.InspectionDetailDTO;
import com.hsteach.web.controller.patrol.dto.InspectionExportDTO;
import com.hsteach.web.controller.patrol.dto.QueryInspectionDTO;
import com.hsteach.web.controller.patrol.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author mgb
 * @version InspectionService, java v1.0 2023-11-22 1:04 EXP $
 */
@Service
@Slf4j
public class InspectionService {

    @Resource
    public InspectionMapper inspectionMapper;

    @Autowired
    public BaseRuleService baseRuleService;

    @Autowired
    public BehaviorCategoryService behaviorCategoryService;

    @Autowired
    private XgkService xgkService;


    /**
     * 分页查询班级巡查得分
     *
     * @param queryInspectionDTO
     * @return
     */
    public TableDataInfo<InspectionDetailVO> list(QueryInspectionDTO queryInspectionDTO) {
        PageHelper.startPage(queryInspectionDTO.getPageNum(), queryInspectionDTO.getPageSize());
        List<InspectionDetail> inspectionDetails = inspectionMapper.listInspection(queryInspectionDTO);
        // 模型转换并赋值
        List<InspectionDetailVO> detailVOS = inspectionDetailConvert(inspectionDetails);
        Long total = new PageInfo(inspectionDetails).getTotal();
        TableDataInfo<InspectionDetailVO> tableDataInfo = new TableDataInfo(detailVOS, total);
        return tableDataInfo;
    }

    private List<InspectionDetailVO> inspectionDetailConvert(List<InspectionDetail> inspectionDetails) {
        List<InspectionDetailVO> detailVOS = new ArrayList<>();
        for (InspectionDetail inspectionDetail : inspectionDetails) {
            InspectionDetailVO detailVO = new InspectionDetailVO();
            detailVO.setId(inspectionDetail.getId());
            detailVO.setGrade(inspectionDetail.getGrade());
            detailVO.setClasses(inspectionDetail.getClasses());
            detailVO.setCreateTime(inspectionDetail.getCreateTime());
            detailVO.setCreator(inspectionDetail.getInspector());
            detailVO.setClassTeacherNumber(inspectionDetail.getClassTeacherNumber());
            detailVO.setClassTeacherName(inspectionDetail.getClassTeacherName());
            detailVO.setInspector(inspectionDetail.getInspector());
            detailVO.setInspectorCode(inspectionDetail.getInspectorCode());
            detailVO.setBehaviorCategory(inspectionDetail.getBehaviorCategory());
            detailVO.setBehaviorName(inspectionDetail.getBehaviorName());
            detailVO.setBehaviorDetail(inspectionDetail.getBehaviorDetail());
            detailVO.setBehaviorScore(inspectionDetail.getBehaviorScore());
            detailVO.setRemark(inspectionDetail.getRemark());
            if (Objects.nonNull(inspectionDetail.getImages())) {
                List<String> imageUrls = JsonUtils.fromJson(inspectionDetail.getImages(), new TypeReference<List<String>>() {
                });
                detailVO.setImages(imageUrls);
            }
            if (Objects.nonNull(inspectionDetail.getOperatorRecord())) {
                List<OperationRecordVO> operationRecordVOS = JsonUtils.fromJson(inspectionDetail.getOperatorRecord(), new TypeReference<List<OperationRecordVO>>() {
                });
                detailVO.setOperatorRecordS(operationRecordVOS);
            }

            detailVO.setIsDelete(DeleteStatusEnum.getInByCode(inspectionDetail.getIsDelete()));
            detailVO.setStatus(StatusEnum.getInByCode(inspectionDetail.getStatus()));

            detailVOS.add(detailVO);

        }
        return detailVOS;
    }


    /**
     * 获取我的记录
     *
     * @param queryInspectionDTO
     */
    public List<InspectionDetailVO> getRecordByUseCode(QueryInspectionDTO queryInspectionDTO) {
        List<InspectionDetail> inspectionDetails = inspectionMapper.getRecordByUseCode(queryInspectionDTO);
        List<InspectionDetailVO> inspectionDetailVOS = InspectionDetailVOConvert(inspectionDetails);
        return inspectionDetailVOS;
    }

    /**
     * 班级巡查得分
     *
     * @param queryInspectionDTO
     * @return
     */
    public TableDataInfo<InspectionScoreVO> queryInspectionByClass(QueryInspectionDTO queryInspectionDTO) {
        // 查询基本配置信息 基本分数，平分周期
        List<BaseConfigVO> baseConfigVOS = baseRuleService.queryBaseConfig(queryInspectionDTO.getOrgCode());
        Map<String, BaseConfigVO> configVOMap = baseConfigVOS.stream().collect(Collectors.toMap(BaseConfigVO::getConfigName, Function.identity()));
        BigDecimal baseScore = new BigDecimal(configVOMap.get(BaseConfigEnum.BASE_SCORE.getName()).getValue());

        List<InspectionScoreVO> inspectionScoreVos = new ArrayList<>();
        //获取前端传递数据集合的班级ID
        List<String> classesIds = queryInspectionDTO.getGradeAndClasses().stream().filter(gradeAndClass -> StringUtils.isNotEmpty(gradeAndClass.getClassId()))
                .map(GradeAndClass::getClassId)
                .distinct()
                .collect(Collectors.toList());
        queryInspectionDTO.setClassIds(classesIds);
        //获取传递数据集合的年级ID
        List<String> gradeIds = queryInspectionDTO.getGradeAndClasses().stream().map(GradeAndClass::getGradeId)
                .distinct().collect(Collectors.toList());
        queryInspectionDTO.setGradeIds(gradeIds);
        //获取分页参数
        Integer pageNum = queryInspectionDTO.getPageNum();
        Integer pageSize = queryInspectionDTO.getPageSize();
        queryInspectionDTO.setPageSize(null);
        List<InspectionDetail> inspectionDetails = inspectionMapper.listInspection(queryInspectionDTO);
        // 过滤出查询参数班级不为空的年级班级信息
        List<GradeAndClass> filterGradeList = queryInspectionDTO.getGradeAndClasses().stream().filter(gradeAndClass -> Objects.nonNull(gradeAndClass.getClassId())).collect(Collectors.toList());
        //查询结果转化为Map
        Map<String/*年级id*/, Map<String/*班级id*/, List<InspectionDetail>>> queryGrade2ClassMap = inspectionDetails.stream()
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getGradeId()))
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getClassesId()))
                .collect(Collectors.groupingBy(InspectionDetail::getGradeId, Collectors.groupingBy(InspectionDetail::getClassesId)));
        //请求参数转化为Map
        Map<String/*年级id*/, Map<String/*班级id*/, List<GradeAndClass>>> sourceGrade2ClassMap = filterGradeList.stream().collect(Collectors.groupingBy(GradeAndClass::getGradeId, Collectors.groupingBy(GradeAndClass::getClassId)));
        if (MapUtils.isEmpty(queryGrade2ClassMap)) {
            // 查询结果为空，则返回查询参数，且分数设置为默认分数
            sourceGrade2ClassMap.forEach((gradeKey, calssMap) -> {
                calssMap.forEach((classId, value) -> {
                    GradeAndClass gradeAndClass = value.get(0);
                    InspectionScoreVO inspectionScoreVO = new InspectionScoreVO();
                    inspectionScoreVO.setGrade(gradeAndClass.getGradeName());
                    inspectionScoreVO.setClasses(gradeAndClass.getClassName());
                    inspectionScoreVO.setClassesId(classId);
                    inspectionScoreVO.setGradeId(gradeKey);
                    inspectionScoreVO.setTotalScore(baseScore.intValue());
                    inspectionScoreVos.add(inspectionScoreVO);
                });
            });

        } else {
            // 结果集不为空，遍历查询结果
            queryGrade2ClassMap.forEach((gradeId, classMap) -> {
                // 对应年级打过分
                classMap.forEach((classId, value) -> {
                    InspectionDetail inspection = value.get(0);
                    InspectionScoreVO inspectionScoreVO = new InspectionScoreVO();
                    // 对应班级打过分
                    // 计算每个班级的加减分的总和
                    BigDecimal score = value.stream()
                            .filter(Objects::nonNull)
                            .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                            .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                            .map(InspectionDetail::getBehaviorScore)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    // 总分数
                    BigDecimal totalScore = baseScore.add(score);
                    inspectionScoreVO.setGrade(inspection.getGrade());
                    inspectionScoreVO.setGradeId(gradeId);
                    inspectionScoreVO.setClasses(inspection.getClasses());
                    inspectionScoreVO.setClassesId(classId);
                    inspectionScoreVO.setTotalScore(totalScore.intValue());
                    inspectionScoreVos.add(inspectionScoreVO);
                });

                // 有的班级没打分就设置为默认分数
                Map<String, List<GradeAndClass>> sourceClassMap = sourceGrade2ClassMap.get(gradeId);
                // 对应年级打过分
                if (MapUtils.isNotEmpty(sourceClassMap)) {
                    sourceClassMap.forEach((classId, value) -> {
                        List<InspectionDetail> inspectionDetails1 = classMap.get(classId);
                        //为空，说明本地没有记录，即没打过分
                        if (CollectionUtils.isEmpty(inspectionDetails1)) {
                            GradeAndClass gradeAndClass = value.get(0);
                            InspectionScoreVO inspectionScoreVO = new InspectionScoreVO();
                            inspectionScoreVO.setGrade(gradeAndClass.getGradeName());
                            inspectionScoreVO.setGradeId(gradeId);
                            inspectionScoreVO.setClasses(gradeAndClass.getClassName());
                            inspectionScoreVO.setClassesId(classId);
                            inspectionScoreVO.setTotalScore(baseScore.intValue());
                            inspectionScoreVos.add(inspectionScoreVO);
                        }

                    });
                }
            });
        }
        // 打过分的和 全部的年级班级未打过分的(返回数据)
        Map<String, Map<String, List<InspectionScoreVO>>> inspectionMap = inspectionScoreVos.stream().collect(Collectors.groupingBy(InspectionScoreVO::getGradeId, Collectors.groupingBy(InspectionScoreVO::getClassesId)));
        //遍历传递参数
        sourceGrade2ClassMap.forEach((sourceGradeId, sourceClassMap) -> {
            Map<String, List<InspectionScoreVO>> inspectedMap = inspectionMap.get(sourceGradeId);
            if (MapUtils.isEmpty(inspectedMap)) {
                sourceClassMap.forEach((classId, value) -> {
                    if (!CollectionUtils.isEmpty(value)) {
                        InspectionScoreVO inspectionScoreVO = new InspectionScoreVO();
                        GradeAndClass gradeAndClass = value.get(0);
                        inspectionScoreVO.setGrade(gradeAndClass.getGradeName());
                        inspectionScoreVO.setClasses(gradeAndClass.getClassName());
                        inspectionScoreVO.setTotalScore(baseScore.intValue());
                        inspectionScoreVO.setClassesId(classId);
                        inspectionScoreVO.setGradeId(sourceGradeId);
                        inspectionScoreVos.add(inspectionScoreVO);
                    }

                });

            }
        });

        Long total = new PageInfo(inspectionScoreVos).getTotal();

        List<InspectionScoreVO> pageList = inspectionScoreVos.stream().skip((pageNum - 1) * pageSize).limit(pageSize).
                collect(Collectors.toList());
        TableDataInfo<InspectionScoreVO> tableDataInfo = new TableDataInfo(pageList, total);
        return tableDataInfo;
    }

    public InspectionScoreDetailVO queryInspectionScoreDetail(QueryInspectionDTO queryInspectionDTO) {
        InspectionScoreDetailVO inspectionScoreDetailVO = new InspectionScoreDetailVO();
        // 查询基本配置信息 基本分数，平分周期
        List<BaseConfigVO> baseConfigVOS = baseRuleService.queryBaseConfig(queryInspectionDTO.getOrgCode());
        Map<String, BaseConfigVO> configVOMap = baseConfigVOS.stream().collect(Collectors.toMap(BaseConfigVO::getConfigName, Function.identity()));
        BigDecimal baseScore = new BigDecimal(configVOMap.get(BaseConfigEnum.BASE_SCORE.getName()).getValue());

        List<InspectionDetail> inspectionDetails = inspectionMapper.listInspection(queryInspectionDTO);
        if (CollectionUtils.isEmpty(inspectionDetails)) {
            ScoreVO scoreVO = new ScoreVO();
            scoreVO.setTotalScore(baseScore);
            scoreVO.setAddTotalScore(new BigDecimal(0));
            scoreVO.setReduceTotalScore(new BigDecimal(0));
            inspectionScoreDetailVO.setScoreVO(scoreVO);
            return inspectionScoreDetailVO;
        }

        // 计算所有分数
        calculateScore(inspectionScoreDetailVO, inspectionDetails, baseScore);

        List<InspectionDetailVO> detailVOS = inspectionDetailConvert(inspectionDetails);
        Map<String, Map<String, List<InspectionDetailVO>>> behaviorAndCategoryAndDescMap = detailVOS.stream()
                .filter(inspectionDetailVO -> Objects.nonNull(inspectionDetailVO.getBehaviorName()))
                .collect(Collectors.groupingBy(InspectionDetailVO::getBehaviorCategory, Collectors.groupingBy(InspectionDetailVO::getBehaviorName)));
        inspectionScoreDetailVO.setBehaviorAndCategoryAndDescMap(behaviorAndCategoryAndDescMap);
        return inspectionScoreDetailVO;
    }

    private void calculateScore(InspectionScoreDetailVO inspectionScoreDetailVO,
                                List<InspectionDetail> inspectionDetails,
                                BigDecimal baseScore) {
        // 计算改班级所有分的合
        BigDecimal totalScore = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorScore()))
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算加分合计
        BigDecimal addScoreTotal = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorScore()))
                .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() >= 0)
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算减分合计
        BigDecimal reduceScoreTotal = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorScore()))
                .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() < 0)
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        ScoreVO scoreVO = new ScoreVO();
        scoreVO.setTotalScore(totalScore.add(baseScore));
        scoreVO.setAddTotalScore(addScoreTotal);
        scoreVO.setReduceTotalScore(reduceScoreTotal);
        inspectionScoreDetailVO.setScoreVO(scoreVO);

        Map<String/*行为*/, List<InspectionDetail>> behaviorMap = inspectionDetails.stream()
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorCategory()))
                .collect(Collectors.groupingBy(InspectionDetail::getBehaviorCategory));
        //计算每个行为的分数
        Map<String, Integer> behaviorScoreMap = new HashMap<>();
        behaviorMap.forEach((behavior, value) -> {
            BigDecimal behaviorScore = value.stream()
                    .filter(Objects::nonNull)
                    .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                    .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                    .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorScore()))
                    .map(InspectionDetail::getBehaviorScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            behaviorScoreMap.put(behavior, behaviorScore.intValue());
        });
        inspectionScoreDetailVO.setBehaviorScore(behaviorScoreMap);

        //计算每个行为分类的分数，二级目录不为空的分类
        Map<String, Map<String, List<InspectionDetail>>> behaviorCategoryMap = inspectionDetails.stream()
                .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                .collect(Collectors.groupingBy(InspectionDetail::getBehaviorCategory,
                        Collectors.groupingBy(InspectionDetail::getBehaviorName)));
        Map<String, Map<String, Integer>> behaviorCategoryScoreMap = new HashMap<>();
        behaviorCategoryMap.forEach((behavior, categoryMap) -> {
            Map<String, Integer> categoryScoreMap = new HashMap<>();
            categoryMap.forEach((category, value) -> {
                BigDecimal behaviorCategoryScore = value.stream()
                        .filter(Objects::nonNull)
                        .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorName()))
                        .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                        .filter(inspectionDetail -> Objects.nonNull(inspectionDetail.getBehaviorScore()))
                        .map(InspectionDetail::getBehaviorScore)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                categoryScoreMap.put(category, behaviorCategoryScore.intValue());
            });
            behaviorCategoryScoreMap.put(behavior, categoryScoreMap);
        });

        inspectionScoreDetailVO.setBehaviorCategoryScore(behaviorCategoryScoreMap);

    }

    public int addInspection(InspectionDetailDTO inspectionDetailDTO) {
        InspectionDetail inspectionDetail = InspectionDetailConvert(inspectionDetailDTO);
        return inspectionMapper.add(inspectionDetail);
    }


    public InspectionDetailAPPVO detailToApp(QueryInspectionDTO queryInspectionDTO) {
        InspectionDetailAPPVO appvo = new InspectionDetailAPPVO();
        // 查询基本配置信息 基本分数，平分周期
        List<BaseConfigVO> baseConfigVOS = baseRuleService.queryBaseConfig(queryInspectionDTO.getOrgCode());
        Map<String, BaseConfigVO> configVOMap = baseConfigVOS.stream().collect(Collectors.toMap(BaseConfigVO::getConfigName, Function.identity()));
        BigDecimal baseScore = new BigDecimal(configVOMap.get(BaseConfigEnum.BASE_SCORE.getName()).getValue());

        List<InspectionDetail> inspectionDetails = inspectionMapper.listInspection(queryInspectionDTO);

        BigDecimal score = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalScore = baseScore.add(score);
        appvo.setTotalScore(totalScore.intValue());
        List<InspectionDetailVO> inspectionDetailVOs = InspectionDetailVOConvert(inspectionDetails);
        appvo.setInspectionDetails(inspectionDetailVOs);
        return appvo;
    }

    /**
     * 班级巡查得分导出
     *
     * @param inspectionExportDTO
     * @return
     */
    public ExportVo exportClassSore(InspectionExportDTO inspectionExportDTO) {
        ExportVo exportVo = new ExportVo();
        // 查询基本配置信息 基本分数，平分周期
        List<BaseConfigVO> baseConfigVOS = baseRuleService.queryBaseConfig(inspectionExportDTO.getOrgCode());
        Map<String, BaseConfigVO> configVOMap = baseConfigVOS.stream().collect(Collectors.toMap(BaseConfigVO::getConfigName, Function.identity()));
        BigDecimal baseScore = new BigDecimal(configVOMap.get(BaseConfigEnum.BASE_SCORE.getName()).getValue());

        List<InspectionDetail> inspectionDetails = inspectionMapper.export(inspectionExportDTO);
        ScoreVO scoreVO = new ScoreVO();
        if (CollectionUtils.isEmpty(inspectionDetails)) {
            scoreVO.setTotalScore(baseScore);
            scoreVO.setAddTotalScore(new BigDecimal(0));
            scoreVO.setReduceTotalScore(new BigDecimal(0));
            exportVo.setScoreVO(scoreVO);
            return exportVo;
        }
        List<InspectionExportVO> inspectionExportVOS = InspectionExportVOConvert(inspectionDetails);
        exportVo.setDataList(inspectionExportVOS);
        // 计算改班级所有分的合
        BigDecimal totalScore = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算加分合计
        BigDecimal addScoreTotal = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() >= 0)
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        // 计算减分合计
        BigDecimal reduceScoreTotal = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() < 0)
                .map(InspectionDetail::getBehaviorScore)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        scoreVO.setTotalScore(totalScore.add(baseScore));
        scoreVO.setAddTotalScore(addScoreTotal);
        scoreVO.setReduceTotalScore(reduceScoreTotal);

        exportVo.setScoreVO(scoreVO);
        return exportVo;
    }

    public ExportVo2 exportClassSore2(InspectionExportDTO inspectionExportDTO) {
        ExportVo2 exportVo = new ExportVo2();
        // 查询基本配置信息 基本分数，平分周期
        List<BaseConfigVO> baseConfigVOS = baseRuleService.queryBaseConfig(inspectionExportDTO.getOrgCode());
        Map<String, BaseConfigVO> configVOMap = baseConfigVOS.stream().collect(Collectors.toMap(BaseConfigVO::getConfigName, Function.identity()));
        BigDecimal baseScore = new BigDecimal(configVOMap.get(BaseConfigEnum.BASE_SCORE.getName()).getValue());
        //导出数据获取
        List<InspectionDetail> inspectionDetails = inspectionMapper.exportScore(inspectionExportDTO);
        List<InspectionExportVo2> inspectionExportVOS = InspectionExportVOConvert2(inspectionDetails, baseScore);
        exportVo.setDataList(inspectionExportVOS);
        //计算总分
        ScoreVO scoreVO = new ScoreVO();
        if (CollectionUtils.isEmpty(inspectionDetails)) {
            scoreVO.setTotalScore(baseScore);
            scoreVO.setAddTotalScore(new BigDecimal(0));
            scoreVO.setReduceTotalScore(new BigDecimal(0));
            exportVo.setScoreVO(scoreVO);
        }else {
            // 计算改班级所有分的合
            BigDecimal totalScore = inspectionDetails.stream()
                    .filter(Objects::nonNull)
                    .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                    .map(InspectionDetail::getBehaviorScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            // 计算加分合计
            BigDecimal addScoreTotal = inspectionDetails.stream()
                    .filter(Objects::nonNull)
                    .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                    .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() >= 0)
                    .map(InspectionDetail::getBehaviorScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            // 计算减分合计
            BigDecimal reduceScoreTotal = inspectionDetails.stream()
                    .filter(Objects::nonNull)
                    .filter(inspectionDetail -> StatusEnum.UN_CANCEL.getCode() == inspectionDetail.getStatus())
                    .filter(inspectionDetail -> inspectionDetail.getBehaviorScore().intValue() < 0)
                    .map(InspectionDetail::getBehaviorScore)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            scoreVO.setTotalScore(totalScore.add(baseScore));
            scoreVO.setAddTotalScore(addScoreTotal);
            scoreVO.setReduceTotalScore(reduceScoreTotal);
            exportVo.setScoreVO(scoreVO);
        }
        return exportVo;
    }

    private List<InspectionExportVo2> InspectionExportVOConvert2(List<InspectionDetail> inspectionDetails, BigDecimal baseScore) {
        //将BigDecimal转换为字符串
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        String baseScoreString = decimalFormat.format(baseScore);
        List<InspectionExportVo2> inspectionExportVOS = new ArrayList<>();
        //数据分组key1：年级，key2：班级：value：对应数据列表
        Map<String, Map<String, List<InspectionDetail>>> dataMapGroupByGradeAndClass = inspectionDetails.stream()
                .filter(Objects::nonNull)
                .filter((e) -> !ObjectUtils.isEmpty(e.getClasses()))
                .filter((e) -> !ObjectUtils.isEmpty(e.getGrade()))
                .collect(Collectors.groupingBy(InspectionDetail::getGrade, Collectors.groupingBy(InspectionDetail::getClasses)));
        //保存分数已经变动的班级信息：格式：年级@=@班级
        ArrayList<String> haveScoreChange = new ArrayList<>();
        //计算总分
        dataMapGroupByGradeAndClass.forEach((grade, classMap) -> {
            classMap.forEach((classes, dataMap) -> {
                InspectionExportVo2 inspectionExportVo2 = new InspectionExportVo2();
                inspectionExportVo2.setGrade(grade);
                inspectionExportVo2.setClasses(classes);
                //计算分数变动值
                BigDecimal scoreSum = dataMap.stream()
                        .filter(Objects::nonNull)
                        .map(InspectionDetail::getBehaviorScore)
                        .filter(behaviorScore -> !ObjectUtils.isEmpty(behaviorScore))
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                String scoreResult = decimalFormat.format(baseScore.add(scoreSum));
                inspectionExportVo2.setTotalScore(scoreResult);
                inspectionExportVOS.add(inspectionExportVo2);
                haveScoreChange.add(inspectionExportVo2.getGrade() + "@=@" + inspectionExportVo2.getClasses());
            });
        });
        //结果数据加上分数未扣的
        List<GetSchoolPartTreeRet> allGrade = xgkService.getAllGrade(SecurityUtils.getAuthInfo().getOrgCode());
        allGrade.stream()
                .filter(Objects::nonNull)
                .filter(e -> StringUtils.isNotEmpty(e.getUnitName()))
                .forEach(gradeNode -> {
                    List<GetSchoolPartTreeRet> classNode = gradeNode.getChildren();
                    classNode.stream()
                            .filter(Objects::nonNull)
                            .filter(e -> StringUtils.isNotEmpty(e.getUnitName()))
                            .forEach(item -> {
                                String nowItem = gradeNode.getUnitName() + "@=@" + item.getUnitName();
                                //如果分数改变记录列表里面没有nowItem，就表示本地没有记录过分数修改，分数就是默认值
                                if (!haveScoreChange.contains(nowItem)) {
                                    InspectionExportVo2 inspectionExportVo2 = new InspectionExportVo2();
                                    inspectionExportVo2.setTotalScore(baseScoreString);
                                    inspectionExportVo2.setGrade(gradeNode.getUnitName());
                                    inspectionExportVo2.setClasses(item.getUnitName());
                                    inspectionExportVOS.add(inspectionExportVo2);
                                }
                            });
                });
        //结果排序
        inspectionExportVOS.sort(((o1, o2) -> {
            BigDecimal o1Score = new BigDecimal(o1.getTotalScore());
            BigDecimal o2Score = new BigDecimal(o2.getTotalScore());
            return o1Score.compareTo(o2Score);
        }));
        return inspectionExportVOS;
    }

    private List<InspectionExportVO> InspectionExportVOConvert(List<InspectionDetail> inspectionDetails) {
        if (CollectionUtils.isEmpty(inspectionDetails)) {
            return new ArrayList<>();
        }
        List<InspectionExportVO> inspectionExportVOS = new ArrayList<>();
        for (InspectionDetail inspectionDetail : inspectionDetails) {
            InspectionExportVO inspectionExportVO = new InspectionExportVO();
            inspectionExportVO.setClasses(inspectionDetail.getClasses());
            inspectionExportVO.setCreateTime(inspectionDetail.getCreateTime());
            String behaviorCategory = inspectionDetail.getBehaviorCategory() + "-->" + inspectionDetail.getBehaviorName();
            inspectionExportVO.setBehaviorCategory(behaviorCategory);
            inspectionExportVO.setBehaviorDetail(inspectionDetail.getBehaviorDetail());
            inspectionExportVO.setScore(inspectionDetail.getBehaviorScore().intValue());
            inspectionExportVO.setCreator(inspectionDetail.getInspector());
            if (Objects.nonNull(inspectionDetail.getModifyTime())) {
                inspectionExportVO.setModifyTime(inspectionDetail.getModifyTime());
            }
            inspectionExportVO.setStatus(StatusEnum.getInByCode(inspectionDetail.getStatus()).getDesc());
            inspectionExportVOS.add(inspectionExportVO);
            String images = inspectionDetail.getImages();
            if (images != null && !images.isEmpty()) {
                images = images.substring(1, images.length() - 1); // 去掉首尾的 []
            }
            inspectionExportVO.setImages(images);
        }
        return inspectionExportVOS;
    }


    private List<InspectionDetailVO> InspectionDetailVOConvert(List<InspectionDetail> inspectionDetails) {
        if (CollectionUtils.isEmpty(inspectionDetails)) {
            return new ArrayList<>();
        }
        List<InspectionDetailVO> inspectionDetailVOS = new ArrayList<>();
        for (InspectionDetail inspectionDetail : inspectionDetails) {
            InspectionDetailVO inspectionDetailVO = new InspectionDetailVO();
//            inspectionDetailVO.setTotalScore(in);
            inspectionDetailVO.setId(inspectionDetail.getId());
            inspectionDetailVO.setGrade(inspectionDetail.getGrade());
            inspectionDetailVO.setClasses(inspectionDetail.getClasses());
            inspectionDetailVO.setCreateTime(inspectionDetail.getCreateTime());
            inspectionDetailVO.setModifyTime(inspectionDetail.getModifyTime());
            inspectionDetailVO.setCreator(inspectionDetail.getInspector());
            inspectionDetailVO.setClassTeacherNumber(inspectionDetail.getClassTeacherName());
            inspectionDetailVO.setClassTeacherName(inspectionDetail.getClassTeacherName());
            inspectionDetailVO.setInspector(inspectionDetail.getInspector());
            inspectionDetailVO.setInspectorCode(inspectionDetail.getInspectorCode());
            inspectionDetailVO.setBehaviorCategory(inspectionDetail.getBehaviorCategory());
            inspectionDetailVO.setBehaviorName(inspectionDetail.getBehaviorName());
            inspectionDetailVO.setBehaviorDetail(inspectionDetail.getBehaviorDetail());
            inspectionDetailVO.setBehaviorScore(inspectionDetail.getBehaviorScore());
            inspectionDetailVO.setRemark(inspectionDetail.getRemark());
            if (Objects.nonNull(inspectionDetail.getImages())) {
                List<String> images = JsonUtils.fromJson(inspectionDetail.getImages(), new TypeReference<List<String>>() {
                });
                inspectionDetailVO.setImages(images);
            }

            if (Objects.nonNull(inspectionDetail.getOperatorRecord())) {
                List<OperationRecordVO> operationRecordVOS = JsonUtils.fromJson(inspectionDetail.getOperatorRecord(), new TypeReference<List<OperationRecordVO>>() {
                });
                inspectionDetailVO.setOperatorRecordS(operationRecordVOS);
            }

            inspectionDetailVO.setIsDelete(DeleteStatusEnum.getInByCode(inspectionDetail.getIsDelete()));
            inspectionDetailVO.setStatus(StatusEnum.getInByCode(inspectionDetail.getStatus()));
            inspectionDetailVO.setRemark(inspectionDetail.getRemark());
            inspectionDetailVOS.add(inspectionDetailVO);
        }
        return inspectionDetailVOS;
    }

    private InspectionDetail InspectionDetailConvert(InspectionDetailDTO inspectionDetailDTO) {
        InspectionDetail inspectionDetail = new InspectionDetail();
        inspectionDetail.setId(inspectionDetailDTO.getId());
        inspectionDetail.setGrade(inspectionDetailDTO.getGrade());
        inspectionDetail.setGradeId(inspectionDetailDTO.getGradeId());
        inspectionDetail.setClasses(inspectionDetailDTO.getClasses());
        inspectionDetail.setClassesId(inspectionDetailDTO.getClassId());
        inspectionDetail.setCreateTime(inspectionDetailDTO.getCreateTime());
        inspectionDetail.setModifyTime(inspectionDetailDTO.getModifyTime());
        inspectionDetail.setClassTeacherNumber(inspectionDetailDTO.getClassTeacherNumber());
        inspectionDetail.setClassTeacherName(inspectionDetailDTO.getClassTeacherName());
        inspectionDetail.setInspector(inspectionDetailDTO.getInspector());
        inspectionDetail.setInspectorCode(inspectionDetailDTO.getInspectorCode());
        inspectionDetail.setBehaviorCategory(inspectionDetailDTO.getBehaviorCategory());
        inspectionDetail.setBehaviorName(inspectionDetailDTO.getBehaviorName());
        inspectionDetail.setBehaviorDetail(inspectionDetailDTO.getBehaviorDetail());
        inspectionDetail.setBehaviorId(inspectionDetailDTO.getBehaviorId());
        inspectionDetail.setBehaviorScore(inspectionDetailDTO.getBehaviorScore());
        inspectionDetail.setRemark(inspectionDetailDTO.getRemark());
        String images = JsonUtils.toJson(inspectionDetailDTO.getImages());
        inspectionDetail.setImages(images);
        String operatorRecord = JsonUtils.toJson(inspectionDetailDTO.getOperatorRecordS());
        inspectionDetail.setOperatorRecord(operatorRecord);
        inspectionDetail.setIsDelete(inspectionDetailDTO.getIsDelete());
        inspectionDetail.setStatus(inspectionDetailDTO.getStatus());
        inspectionDetail.setOrgCode(inspectionDetailDTO.getOrgCode());
        return inspectionDetail;
    }


    // 更新分类名称
    public void updateOrdinanceById(List<Behavior> behaviors) {
        for (Behavior behavior : behaviors) {
            inspectionMapper.updateOrdinanceById(behavior);
        }
    }


    public List<InspectionDetail> queryInspectionByBehaviorId(int behaviorId) {
        return inspectionMapper.queryInspectionByBehaviorId(behaviorId);
    }

    public int deleteInspection(InspectionDetailDTO inspectionDetailDTO) {
        String operatorRecord = JsonUtils.toJson(inspectionDetailDTO.getOperatorRecordS());
        return inspectionMapper.deleteInspection(inspectionDetailDTO.getId(), operatorRecord);
    }

    public HashMap<String,Object> statisticsAreaApp() {
        List<InspectionDetail> inspectionDetails = inspectionMapper.listInspection(new QueryInspectionDTO()).stream().filter(it->!Arrays.asList("cdsslqjfxx", "jfzx", "slqjfwgyxx", "jfcjzx","518129940222865408").contains(it.getOrgCode())).collect(Collectors.toList());
        Set<String> orgSet = inspectionDetails.stream().map(InspectionDetail::getOrgCode).collect(Collectors.toSet());
        return new HashMap<String,Object>(){{
            put("orgNum",orgSet.size());
            put("num",inspectionDetails.size());
        }};
    }
}
